package org.smile.pager.extremecomponents;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.smile.db.PageModel;
import org.smile.pager.Pager;
/**
 * 适用于jsptags分页标签的一个实现
 * @author strive
 *
 */
public class EcPager implements Pager {
	/**
	 * 每页显示条数
	 */
	private int size=15;
	/**
	 * 当前页
	 */
	private int page=1;
	
	private String id="ec";
	
	private HttpServletRequest request=null;
	
	public EcPager(HttpServletRequest request){
		this.request=request;
		refreshPage();
	}
	public EcPager(HttpServletRequest request,int size){
		this.request=request;
		refreshPage();
		this.size=size;
	}
	/**
	 * 
	 */
	public void refreshPage() {
		try{
			String pageStr=request.getParameter(id+"_p");
			if(pageStr!=null&&!"".equals(pageStr)){
				this.page=Integer.parseInt(pageStr);
			}
			String crd=request.getParameter(id+"_crd");
			if(crd!=null&&!"".equals(crd)){
				size=Integer.parseInt(crd);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void setId(String id){
		this.id=id;
		int size=this.size;
		refreshPage();
		this.size=size;
	}
	public void commitResult(PageModel pageModel) {
		request.setAttribute("pageModel", pageModel);
		request.setAttribute("totalRows", new Integer((int)pageModel.getTotal()));
	}
	public int getPage() {
		return page;
	}

	public HttpServletRequest getRequest() {
		return request;
	}
	public int getSize() {
		return size;
	}
	
	public Map getParameterMap() {
		String startWith=id+"_f_";
		Map map=new HashMap();
		Enumeration enums=request.getParameterNames();
		while(enums.hasMoreElements()){
			Object name=enums.nextElement();
			if(name instanceof String){
				String nameStr=(String)name;
				if(nameStr.startsWith(startWith,0)){
					map.put(nameStr.substring(startWith.length()), request.getParameter(nameStr));
				}else{
					map.put(nameStr, request.getParameterValues(nameStr));
				}
			}
		}
		return map;
	}
}
